package V003_MapLoader;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;

/**
 *
 * @author Smai
 */
public class Map {

  private Tile[][] worldTiles = MapLoader.CreateMap(256, 256,"map01");
  private Player player;
  private int posFocusX;
  private int posFocusY;
  private int WorldArrayX;
  private int WorldArrayY;

  public Map(Game game, Player player) {
    this.player = player;
  }

  public void piirraKartta(Graphics gbi, int width, int height) {

    for (int i = 0; i < 36; i++) {
      for (int j = 0; j < 24; j++) {
        worldTiles[i + WorldArrayX][j + WorldArrayY].paint(gbi, i, j, posFocusX, posFocusY);
      }
    }

    player.paint(gbi);

    //Debuggausta
    gbi.setColor(Color.white);
    gbi.drawString("Focus " + posFocusX + "," + posFocusY, 16, 544);
    gbi.drawString("WorldArray " + WorldArrayX + "," + WorldArrayY, 16, 560);
  }

  public void moving(int x, int y) {
    if (collisionDetection(x, y)) {
      checkArray();
      return;
    } else {
      this.posFocusX = this.posFocusX + x;
      this.posFocusY = this.posFocusY + y;
      checkArray();
    }
  }

  public void checkArray() {

    //Tarkastetaan linjaukset x
    if (posFocusX == -32) {
      posFocusX = 0;
      WorldArrayX--;
    } else if (posFocusX == 32) {
      posFocusX = 0;
      WorldArrayX++;
    }

    //Tarkastetaan linjaukset Y
    if (posFocusY == -32) {
      posFocusY = 0;
      WorldArrayY--;
    } else if (posFocusY == 32) {
      posFocusY = 0;
      WorldArrayY++;
    }
  }

  public boolean collisionDetection(int x, int y) {
    Rectangle playerBoundaries = player.getRectangle(x, y);
    Rectangle blockBoundaries;

    for (int i = 0; i < 36; i++) {
      for (int j = 0; j < 24; j++) {
        blockBoundaries = worldTiles[i + WorldArrayX][j + WorldArrayY].getRectangle();
        if (blockBoundaries == null) {
        } else {
          if (playerBoundaries.intersects(blockBoundaries)) {
            return true;
          }
        }
      }
    }
    return false;
  }
}
